package uml.construct.singleton.ext;

import java.util.ArrayList;

/**
 * 多例类--实例数量可控、可累加<br>
 * on 2022/12/22 0:06
 */
public class MultiInstance {
    private static ArrayList<MultiInstance> instances = null;
    private static final Object ADD_LOCK =new Object();

    private MultiInstance() {
        if (instances == null) {
            synchronized (MultiInstance.class) {
                if (instances == null) {
                    instances = new ArrayList<>();
                }
            }
        }
        if (!instances.contains(this)) {
            synchronized (ADD_LOCK) {
                if (!instances.contains(this)) {
                    instances.add(this);
                }
            }
        }
    }

    /**
     * @param accumulation 实例累加数
     * @return 总实例数组
     */
    public static ArrayList<MultiInstance> getInstances(int accumulation) {
        for (int i = 0; i < accumulation; i++) {
            new MultiInstance();
        }
        return instances;
    }
}
